package com.muse.aaa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.function.Function;

/**
 * HashMap扰动函数测试类
 */
public class SpreadDemo {
    private static final int HASH_BITS = 0x7fffffff; // 0111 1111 1111 1111 1111 1111 1111 1111
    private static final int SIZE = 128;
    private static final File inputFile = new File("src/main/resources/words.txt");
    private static final File outputFile = new File("src/main/resources/result.csv");
    private static final File outputFile1 = new File("src/main/resources/result1.csv");

    public static void main(String[] args) throws Throwable {
        execute(word -> spread(word.hashCode()), outputFile); /** 采用扰动函数计算index下标 */
        execute(word -> word.hashCode(), outputFile1); /** 只采用对象的hashCode计算index下标 */
    }

    public static void execute(Function<String, Integer> function, File outputFile) throws Throwable {
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        String word;
        int index;
        HashMap<Integer, Integer> map = new HashMap();
        while ((word = br.readLine()) != null) {
            index = (SIZE - 1) & function.apply(word);
            Integer num;
            if ((num = map.get(index)) == null) {
                map.put(index, 1);
            } else {
                map.put(index, ++num);
            }
        }
        FileWriter fw = new FileWriter(outputFile);
        for (Integer key : map.keySet()) {
            fw.write(key + "," + map.get(key) + "\n");
        }
        br.close();
        fw.close();
    }

    public static int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
    }
}


